package com.mgq.juc.design.guard.v2;

import java.util.Hashtable;
import java.util.Map;
import java.util.Set;

/**
 * @author MaGuangQi
 * @date 2021-12-16 10:43
 **/
public class MailBoxes {
    /**
     * 此处暂时使用HashTable
     */
    private static Map<Integer, GuardedObject> mailBoxes = new Hashtable<>();
    /**
     * 生成 id
     */
    private static int id = 0;

    /**
     * 创建GuardObject对象
     *
     * @return
     */
    public static GuardedObject createGuardObject() {
        GuardedObject guardedObject = new GuardedObject(generateId());
        mailBoxes.put(guardedObject.getId(), guardedObject);
        return guardedObject;
    }

    /**
     * 生成id
     *
     * @return
     */
    public static synchronized int generateId() {
        return id++;
    }

    /**
     * 获取信件
     *
     * @param id
     * @return
     */
    public static GuardedObject getMail(int id) {
        return mailBoxes.remove(id);
    }

    /**
     * 获取id集合
     *
     * @return
     */
    public static Set<Integer> getIds() {
        return mailBoxes.keySet();
    }
}
